package com.es.hotel.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.es.hotel.main.client.EsIndexClient;
import com.es.hotel.mapper.HotelMapper;
import com.es.hotel.pojo.Hotel;
import com.es.hotel.pojo.HotelDoc;
import com.es.hotel.query.PageResult;
import com.es.hotel.query.RequestParams;
import com.es.hotel.service.IHotelService;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {

    @Override
    public PageResult search(RequestParams params) {
        try {
            //1.准备request
            SearchRequest request = new SearchRequest("hotel");
            //2.1准备请求参数
            buildBasicQuery(params,request);
            //分页
            Integer page = params.getPage();
            Integer size = params.getSize();
            request.source().from((page -1 )*page).size(size);
            //按照距离排序
            String location = params.getLocation();
            if(StringUtils.isNotBlank(location)){
                request.source().sort(SortBuilders
                        .geoDistanceSort("location", new GeoPoint(location))
                        .order(SortOrder.ASC)
                        .unit(DistanceUnit.KILOMETERS));
            }
            //发送请求
            SearchResponse response = EsIndexClient.client().search(request, RequestOptions.DEFAULT);
            return handleResponse(response);
        } catch (IOException e) {
            throw new RuntimeException("搜索失败",e);
        }
    }



    private void buildBasicQuery(RequestParams params, SearchRequest request) {
        //1.准备布尔查询
        BoolQueryBuilder booledQuery = QueryBuilders.boolQuery();
        String key = params.getKey();
        if(StringUtils.isNotBlank(key)){
            //传入关键字就是对关键字进行检索，这个关键字相当于随便填写的词语
            booledQuery.must(QueryBuilders.matchQuery("all", key));
        }else {
            //否则查询所有数据
            booledQuery.must(QueryBuilders.matchAllQuery());
        }

        //这个品牌相当于前端可选的关键字
        String brand = params.getBrand();
        if(StringUtils.isNotBlank(brand)){
            //必须要匹配但是不需要参与算分
            booledQuery.filter(QueryBuilders.termQuery("brand", brand));
        }

        //城市
        String city = params.getCity();
        if (StringUtils.isNotBlank(city)){
            booledQuery.filter(QueryBuilders.termQuery("city",city));
        }

        //星级
        String starName = params.getStarName();
        if(StringUtils.isNotBlank(starName)){
            booledQuery.filter(QueryBuilders.termQuery("startName",starName));
        }

        //价格范围
        Integer minPrice = params.getMinPrice();
        Integer maxPrice = params.getMaxPrice();
        if(minPrice != null && maxPrice != null){
            maxPrice = maxPrice == 0 ? Integer.MAX_VALUE : maxPrice;
            booledQuery.filter(QueryBuilders.rangeQuery("price").gte(minPrice).lte(maxPrice));
        }

        //算分函数
        //当文档中的 isAD 字段为 true 时，这些文档的得分将被提高，得分提高的具体方式是将原始得分乘以10。
        FunctionScoreQueryBuilder isAD = QueryBuilders.functionScoreQuery(
                booledQuery,
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD", true),
                                ScoreFunctionBuilders.weightFactorFunction(10)
                        )
                }
        );

        //设置查询条件
        request.source().query(isAD);
    }

    private PageResult handleResponse(SearchResponse response){
        SearchHits hits = response.getHits();
        long total = hits.getTotalHits().value;
        SearchHit[] searchHits = hits.getHits();
        ArrayList<HotelDoc> result = new ArrayList<>(searchHits.length);
        for(SearchHit hit: searchHits){
            String json = hit.getSourceAsString();
            //非高亮结果
            HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
            //高亮结果显示
            Map<String, HighlightField> map = hit.getHighlightFields();
            if(map != null && !map.isEmpty()){
                HighlightField name = map.get("name");
                if(name != null){
                    String hName = name.getFragments()[0].toString();
                    hotelDoc.setName(hName);
                }
            }
            //排序信息
            Object[] sortValues = hit.getSortValues();
            if(sortValues.length > 0){
                hotelDoc.setDistance(sortValues[0]);
            }
            result.add(hotelDoc);
        }
        return new PageResult(total,result);
    }

    @Override
    public Map<String, List<String>> agg(RequestParams params){
        try {
            SearchRequest request = new SearchRequest("hotel");
            //结合请求参数
            buildBasicQuery(params,request);
            //清空文档信息
            request.source().size(0);
            //对页面静态信息进行聚合
            buildAggregations(request);
            SearchResponse response = EsIndexClient.client().search(request, RequestOptions.DEFAULT);
            //解析结果
            Aggregations aggregations = response.getAggregations();
            HashMap<String, List<String>> map = new HashMap<>(3);
            List<String> brandList = getAggByName(aggregations,"brandAgg");
            map.put("brandList", brandList);
            List<String> cityList = getAggByName(aggregations,"cityAgg");
            map.put("cityList", cityList);
            List<String> starNameList = getAggByName(aggregations,"starAgg");
            map.put("starNameList", starNameList);
            return map;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }



    private void buildAggregations(SearchRequest request) {
        request.source().aggregation(
                AggregationBuilders.terms("brandAgg").field("brand").size(100));
        request.source().aggregation(
                AggregationBuilders.terms("cityAgg").field("city").size(100));
        request.source().aggregation(
                AggregationBuilders.terms("starAgg").field("starName").size(100));
    }
    private List<String> getAggByName(Aggregations aggregations, String aggName) {
        Terms terms = aggregations.get(aggName);
        List<? extends Terms.Bucket> buckets = terms.getBuckets();
        ArrayList<String> list = new ArrayList<>(buckets.size());
        for(Terms.Bucket bucket: buckets){
            String name = bucket.getKeyAsString();
            list.add(name);
        }
        return list;
    }

    @Override
    public List<String> getSuggestion(String key) {
        try {
            SearchRequest request = new SearchRequest("hotel");
            request.source().suggest(new SuggestBuilder()
                    .addSuggestion("hotelSuggest", SuggestBuilders
                            .completionSuggestion("suggestion")  // 这里要使用 suggestion 字段
                            .size(10)
                            .skipDuplicates(true)
                            .prefix(key)));  // 用户输入的前缀

            // 执行查询并解析结果
            SearchResponse response = EsIndexClient.client().search(request, RequestOptions.DEFAULT);
            Suggest suggest = response.getSuggest();
            CompletionSuggestion suggestion = suggest.getSuggestion("hotelSuggest");
            ArrayList<String> list = new ArrayList<>();
            for(CompletionSuggestion.Entry.Option option : suggestion.getOptions()){
                String string = option.getText().toString();
                list.add(string);
            }
            return list;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
